﻿using AudioStudio;
using System;
using System.Collections.Generic;
using System.IO;
using UnityEditor;
using UnityEngine;
using UnityEngine.SceneManagement;
using Yoozoo.Managers.ResourceManagement;
using Yoozoo.Managers.ResourceManagerV2.Runtime;
using Object = UnityEngine.Object;

namespace Yoozoo.Gta.ProjBuilder
{
    public class SubPackageTool
    {
        private static event Action<string> onAssetUsed;

        private static event Action<int> onSetAssetOrder;

        /// <summary>
        /// 提供给Lua层调用的收集资源的接口
        /// </summary>
        /// <param name="assetName"></param>
        public static void UseAsset(string assetName)
        {
            //Debug.LogError("UseAsset: " + assetName);
            onAssetUsed?.Invoke(assetName);
        }

        public static void OnGuideFinish(int order)
        {
        }

        public static void SetAssetOrder(int order)
        {
            onSetAssetOrder?.Invoke(order);
        }

        public static void SetAppConfig(bool isFirstPackage)
        {
            string bundleVersion = AppConfig.BundleVersion;
            int bundleVersionCode = AppConfig.BundleVersionCode;
            string channel = AppConfig.Channel;
            bool isMSDK = AppConfig.IsSDK;
            bool isUpdateResource = AppConfig.IsUpdateResource;
            bool isDebug = false;
            bool isLog = AppConfig.IsLog;
            int packagerResourceTypeIndex = -1;
            string versionControlUrl = AppConfig.VersionControlUrl;
            string secondaryVersionControlUrl1 = AppConfig.SecondaryVersionControlUrl1;
            string secondaryVersionControlUrl2 = AppConfig.SecondaryVersionControlUrl2;
            string serverListPath = AppConfig.ServerListPath;
            string maintenanceUrl = AppConfig.MaintenanceUrl;
            string serverApiPath = AppConfig.ServerApiPath;
            string serverPath = AppConfig.ServerPath;
            bool IsShowGM = AppConfig.IsShowGM;
            AppConfig.SetAppConfig(bundleVersion, bundleVersionCode, channel, isMSDK, isUpdateResource, isDebug, isLog,
                packagerResourceTypeIndex, string.Empty, versionControlUrl, serverListPath, maintenanceUrl, isFirstPackage, serverApiPath,
                secondaryVersionControlUrl1, secondaryVersionControlUrl2,serverPath,IsShowGM);
        }

        public static string[] RpgAssetRootPaths =
        {

        };

        private static string AtlasExtension = ".spriteatlas";

        public static bool IsKnownRpgAsset(string assetPath)
        {
            if (assetPath.EndsWith(".spriteatlas"))
                return true;

            foreach (var rootPath in RpgAssetRootPaths)
            {
                var fixedPath = rootPath + "/";
                if (assetPath.StartsWith(fixedPath))
                {
                    return true;
                }
            }

            return false;
        }

        private static string GetAtlasPath()
        {
            string spriteAtlasPath = ResourceSettings.AtlasPath;

            if (string.IsNullOrEmpty(spriteAtlasPath))
                throw new System.Exception("[Atlas Path] null");
            spriteAtlasPath = spriteAtlasPath.Replace('\\', '/');
            if (!spriteAtlasPath.EndsWith("/"))
                spriteAtlasPath += "/";
            return spriteAtlasPath;
        }

        public static void CollectRpgAssets()
        {

        }



        public static void CollectFirstPackageAssets(string tag)
        {
#if UNITY_EDITOR
            // 设置tag，否则rpg包不加载
            Managers.ResourceManagerV2.Editor.ResourceTools.EditorResourceSettings.AssetPackTags.Add(tag);
            var collection = new Managers.ResourceManagerV2.Editor.ResourceTools.AssetPackListCollection();
            if (!collection.Load())
            {
                Debug.LogError("AssetPackListCollection加载失败");
                return;
            }

            void CollectAsset(string assetName, bool collectSprites = false)
            {
                if (collection.HasAsset(assetName, tag)) return;

                if (assetName.StartsWith(GetAtlasPath()) && !assetName.EndsWith(AtlasExtension))
                {
                    // 精灵图，不收集单一的图片，只收集图集
                    CollectSprite(assetName, collection, tag);
                }
                else if (assetName.EndsWith(".shadervariants") && assetName.Contains("_level"))
                {
                    // 分级的ShaderVariantCollection， 把各个级别都加上去
                    string assetNamePre = assetName.Substring(0, assetName.IndexOf("_level", StringComparison.Ordinal));
                    for (int i = 0; i < 5; i++)
                    {
                        var shaderVariantsName = $"{assetNamePre}_level{i}.shadervariants";
                        collection.AssignAsset(shaderVariantsName, tag);
                        Debug.LogFormat("新增首包资产: {0} {1}", shaderVariantsName, tag);
                    }
                }
                else
                {
                    // 一般的资产
                    collection.AssignAsset(assetName, tag);
                    Debug.LogFormat("新增首包资产: {0} {1}", assetName, tag);
                }

                if (collectSprites)
                {
                    var prefab = AssetDatabase.LoadAssetAtPath<GameObject>(assetName);
                    if (prefab)
                    {
                        var imageAdapters = prefab.GetComponentsInChildren<com.yoozoo.gta.Extension.UGUI.ScreenOrientation.Adapter.YImageAdapter>(true);
                        foreach (var yImageAdapter in imageAdapters)
                        {
                            var portraitImagePath = yImageAdapter.GetPortraitImagePath();
                            if (!string.IsNullOrEmpty(portraitImagePath))
                                CollectAsset(portraitImagePath);

                            var landscapeImagePath = yImageAdapter.GetLandscapeImagePath();
                            if (!string.IsNullOrEmpty(landscapeImagePath))
                                CollectAsset(landscapeImagePath);
                        }
                    }
                }

                collection.Save(tag);
            }

            bool found = false;
            var rootGameObjects = SceneManager.GetActiveScene().GetRootGameObjects();
            foreach (var rootGameObject in rootGameObjects)
            {
                var editorResourceComponent = rootGameObject.GetComponentInChildren<EditorResourceComponent>(true);
                if (editorResourceComponent)
                {
                    found = true;

                    editorResourceComponent.BeforeLoadAssetCallback = assetName => CollectAsset(assetName);
                }
            }

            if (found)
            {
                Debug.Log("开始收集首包资源");
            }
            else
            {
                Debug.LogError("没有找到EditorResourceComponent");
            }

            // 打包的时候BinaryAssets自动进首包

            // 一些编辑器正常流程收集不到的资源
            // 边玩边下时才会弹出的小菊花
            CollectAsset("Assets/ResourcesAssets/Prefabs/UI/Loading/SmallLoadingUI.prefab", true);
            // 边玩边下页面
            CollectAsset("Assets/ResourcesAssets/Prefabs/UI/MainUI/DownloadUI.prefab", true);
            // 维护UI
            CollectAsset("Assets/ResourcesAssets/Prefabs/UI/Tips/MaintenanceUI.prefab", true);
            // 一些通用弹框
            CollectAsset("Assets/ResourcesAssets/Prefabs/UI/Tips/OneBtnTipsUI.prefab", true);
            CollectAsset("Assets/ResourcesAssets/Prefabs/UI/Tips/SystemErrorUI.prefab", true);
            CollectAsset("Assets/ResourcesAssets/Prefabs/UI/Tips/TwoBtnTipsUI.prefab", true);

            // 不同RoleType会加载不同的引导
            // 参考 Assets/ResourcesAssets/Persistent/Blueprint/GuideBlueprint.prefab
            CollectAsset("Assets/ResourcesAssets/Persistent/Blueprint/guideChapter_01.prefab", true);
            CollectAsset("Assets/ResourcesAssets/Persistent/Blueprint/guideChapter_02.prefab", true);
            CollectAsset("Assets/ResourcesAssets/Persistent/Blueprint/guideChapter_03.prefab", true);
            CollectAsset("Assets/ResourcesAssets/Persistent/Blueprint/guideChapter_04.prefab", true);
            CollectAsset("Assets/ResourcesAssets/Persistent/Blueprint/guideChapter_05.prefab", true);

            // 资源校验页面
            CollectAsset("Assets/ResourcesAssets/Prefabs/UI/Loading/VerifyUI.prefab", true);

            // GM面板
            //CollectAsset("Assets/ResourcesAssets/Prefabs/UI/GM/GMPanel.prefab", true);
            //CollectAsset("Assets/ResourcesAssets/Prefabs/UI/GM/GMSubPanel.prefab", true);

            // EmojiCreator里加载
            CollectAsset("Assets/ResourcesAssets/UI/GUI/Emoji64.spriteatlas");
            // EmotePlayer里加载
            CollectAsset("Assets/ResourcesAssets/UI/GUI/ChatEmote.spriteatlas");

            //onAssetUsed += CollectAsset;
            //AudioManager.OnPlayAudio += CollectAsset;
            onSetAssetOrder += order =>
            {
                collection.SetOrder(order, tag);
            };
#endif
        }

#if UNITY_EDITOR
    
        private static void CollectSprite(string assetName, Yoozoo.Managers.ResourceManagerV2.Editor.ResourceTools.AssetPackListCollection collection, string tag)
        {
            string atlasRoot = GetAtlasPath();

            // 精灵，先找到图集
            // asset: Root/a/b/c.png => bundle: Root/a_b.spriteatlas

            string directory = Path.GetDirectoryName(assetName);
            directory = directory.Substring(atlasRoot.Length);
            var subDirs = directory.Split(new []{ '/', '\\'});
            string subDir = subDirs[0];
            if (subDirs[0] == "icon" || subDirs[0] == "Pve" || subDirs[0] == "PrettyGirls" || subDirs[0] == "ResFlySpriteSheet")
            {
                subDir = $"{subDirs[0]}/{subDirs[1]}";
            }

            //string spriteRoot = $"{atlasRoot}/{subDir}";
            var atlasName = subDir.Replace("/", Yoozoo.Managers.ResourceManagerV2.Editor.ResourceTools.EditorResourceSettings.AtlasDirectorySeparator);
            string atlasPath = $"{atlasRoot}{atlasName}{AtlasExtension}";
            if (!collection.HasAsset(atlasPath, tag))
            {
                collection.AssignAsset(atlasPath, tag);
                Debug.LogFormat("新增首包资产: {0} {1}", atlasPath, tag);
            }

            collection.Save(tag);
        }
#endif
    }
}
